package com.project.platform.service.impl;

import com.project.platform.entity.Elder;
import com.project.platform.entity.Room;
import com.project.platform.mapper.ElderMapper;
import com.project.platform.mapper.RoomMapper;
import com.project.platform.service.RoomService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.project.platform.vo.PageVO;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ${table.name}
 */
@Service
public class RoomServiceImpl  implements RoomService {
    @Resource
    private RoomMapper roomMapper;

    @Resource
    private ElderMapper elderMapper;
    
    @Override
    public PageVO<Room> page(Map<String, Object> query, Integer pageNum, Integer pageSize) {
        PageVO<Room> page = new PageVO();
        List<Room> list = roomMapper.queryPage((pageNum - 1) * pageSize, pageSize, query);
        //获取所有的 id
        List<Integer> idList = list.stream().map(Room::getId).toList();
        //汇总出每个房间有多少老人，以及对应的名字
        List<Elder> elders = elderMapper.selectByRoomIds(idList);
        Map<Integer, List<Elder>> elderMap = elders.stream().collect(Collectors.groupingBy(Elder::getRoomId));
        list.forEach(e -> {
            List<Elder> elderList = elderMap.get(e.getId());
            //记录状态，如果为空，则表示房间是空闲的，如果不为空，则表示房间已经有人住了
            e.setStatus(elderList == null ? "空闲" : "已入住");
            //把老人名字拼接起来
            String eldersName = elderList == null ? "" : elderList.stream().map(Elder::getNickname).collect(Collectors.joining(","));
            e.setElderNames(eldersName);
        });
        page.setList(list);
        page.setTotal(roomMapper.queryCount(query));
        return page;
    }


    @Override
    public Room selectById(Integer id) {
        Room room = roomMapper.selectById(id);
        return room;
    }

    @Override
    public List<Room> list() {
        return roomMapper.list();
    }
    @Override
    public void insert(Room entity) {
        check(entity);
        roomMapper.insert(entity);
    }
    @Override
    public void updateById(Room entity) {
        check(entity);
        roomMapper.updateById(entity);
    }
    private void check(Room entity) {

    }
    @Override
    public void removeByIds(List<Integer> ids) {
        roomMapper.removeByIds(ids);
    }

    @Override
    public List<Room> availableRooms() {
        List<Room> list = roomMapper.list();
        //获取所有的 id
        List<Integer> idList = list.stream().map(Room::getId).toList();
        List<Elder> elders = elderMapper.selectByRoomIds(idList);
        Map<Integer, List<Elder>> elderMap = elders.stream().collect(Collectors.groupingBy(Elder::getRoomId));

        //找出空闲房间或者未住满的房间
        return list.stream().filter(e ->{
            List<Elder> elderList = elderMap.get(e.getId());
            return elderList == null || elderList.size() < e.getCapacity();
        }).toList();

    }


}
